package com.wenjiang.http;


import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.wenjiang.Interceptor.HttpInterceptor;
import com.wenjiang.config.LanTuPayProperties;
import com.wenjiang.constant.LanTuPayConstant;
import com.wenjiang.enums.LanTuPayErrorEnum;
import com.wenjiang.exception.LanTuPayException;
import com.wenjiang.factory.HttpRequestInterceptorFactory;
import com.wenjiang.model.request.AbstractWxRequest;
import com.wenjiang.model.response.CommonWxResult;
import lombok.extern.slf4j.Slf4j;


/**
 * <p>
 *  lantu支付http 执行器
 * </p>
 *
 * @author lwj
 * @since 2024/11/29.
 */
@Slf4j
public class LanTuWxPayHttpClient implements LanTuHttpClient<AbstractWxRequest> {
    private LanTuPayProperties lanTuPayProperties;


    public LanTuWxPayHttpClient(LanTuPayProperties lanTuPayProperties) {
        this.lanTuPayProperties = lanTuPayProperties;
    }

    @Override
    public <T> T sendPost(String api, AbstractWxRequest request, Class<T> responseClass) {
        //1.走拦截器 打印日志  校验参数 生成签名
        HttpInterceptor<AbstractWxRequest> httpInterceptor = HttpRequestInterceptorFactory.buildLanTuWxPayHttpRequestInterceptor(lanTuPayProperties);
        AbstractWxRequest abstractWxRequest = httpInterceptor.requestInterceptor(request);
        //2.发送请求
        String formBody = abstractWxRequest.toFormBody();
        String url = LanTuPayConstant.LAN_TU_PAY_API_BASE_URL + api;

        log.info("请求蓝兔支付接口, 请求地址：{} 请求参数:{}",url,JSON.toJSONString(request));
        try {
            // 使用Hutool发送请求
            HttpResponse response = HttpRequest.post(url)
                    .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                    .body(formBody)
                    .timeout(30 * 1000)
                    .execute();

            String responseData = response.body();
            log.info("蓝兔接口响应：{}", responseData);
            if (response.isOk()){
                // 解析返回的 JSON 数据
                CommonWxResult<T> tCommonWxResult = JSON.parseObject(responseData, new TypeReference<CommonWxResult<T>>(responseClass) {});
                Integer code = tCommonWxResult.getCode();
                if (code !=0){
                    throw  new LanTuPayException(LanTuPayErrorEnum.SERVER_ERROR.getCode(),tCommonWxResult.getMsg());
                }
                T data = tCommonWxResult.getData();
                return  data;
            }else {
                log.error("蓝兔失败支付响应：{}",  responseData);
                throw new LanTuPayException("蓝兔支付调用失败!",responseData);
            }
        } catch (Exception e) {
            throw new LanTuPayException("蓝兔支付调用失败!",e.getMessage());
        }
    }
}
